// src/routers/index.ts
import React from "react";
import { createBrowserRouter, RouterProvider, RouteObject } from "react-router-dom";
import Layout from "../components/Layout/index";
import { useStore } from '../stores';
import { routes } from "./routesConfig";
import { ProtectedRoute } from './ProtectedRoute';
import { RouteConfig } from '../types/router.types';

// 将RouteConfig转换为RouteObject，并处理保护路由
const convertRoutes = (routes: RouteConfig[]): RouteObject[] => {
  return routes.map(route => {
    const routeObject: RouteObject = {
      path: route.path,
      element: route.protected 
        ? React.createElement(ProtectedRoute, null, route.element)
        : route.element,
    };

    if (route.children && route.children.length > 0) {
      routeObject.children = convertRoutes(route.children);
    }

    return routeObject;
  });
};

// 路由配置
const router = createBrowserRouter([
  {
    path: "/",
    element: React.createElement(LayoutWrapper, null),
    children: convertRoutes(routes),
  },
]);

// 包装Layout组件以传递store
function LayoutWrapper() {
  const store = useStore();
  // 添加保护性检查，确保 store.ui.layout 存在且有正确的结构
  if (!store.ui || !store.ui.layout) {
    return React.createElement("div", null, "Loading...");
  }
  
  return React.createElement(Layout, { uilayoutStore: store.ui.layout });
}

export function Router() {
  return React.createElement(RouterProvider, { router: router });
}